import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { AggregateQuery } from './AggregateQuery';
import { AggregateResult } from './AggregateResult';

import { format } from 'date-fns';

@Component({
  selector: 'app-aggregateQuery',
  templateUrl: './aggregateQuery.component.html',
  styleUrls: ['./aggregateQuery.component.css'],
})

export class AggregateQueryComponent implements OnInit {

  arithmeticType: string = 'COMMON';

  selectedMetric = '';
  metrics = [];
  nzFilterOption = () => true;

  tagsOfMetric = [];

  tags: Array<{ tagKey: string; tagValue: string }> = [];
  tagValues = [];

  aggregateResults: AggregateResult[] = [];

  constructor(private httpClient: HttpClient) {
  }

  ngOnInit() {
    this.tags.push({ tagKey: '', tagValue: '' });
  }

  onMetricSerach(value: string): void {
    if (value === '') {
      return;
    }
    let url = '/api/metricTag/queryMetric';
    let body: any = {};
    body['metric'] = value;
    this.httpClient.post(url, body, {}).subscribe((data: any) => {
      this.metrics = data;
    });
  }

  queryTagKeyOfMetric() {
    console.log(this.selectedMetric);
    if (this.selectedMetric === '') {
      return;
    }
    let url = '/api/metricTag/queryTagKeyOfMetric';
    let body: any = {};
    body['metric'] = this.selectedMetric;
    this.httpClient.post(url, body, {}).subscribe((data: any) => {
      this.tagsOfMetric = data;
    });
  }

  queryTagValueOfMetric(index: number, value: string) {
    console.log(this.selectedMetric);
    if (this.selectedMetric === '') {
      return;
    }
    let url = '/api/metricTag/queryTagValueOfMetric';
    let body: any = {};
    body['metric'] = this.selectedMetric;
    body['tagKey'] = this.tags[index].tagKey;
    body['tagValue'] = value;
    this.httpClient.post(url, body, {}).subscribe((data: any) => {
      this.tagValues = data;
    });
  }

  addTag(e?: MouseEvent): void {
    if (e) {
      e.preventDefault();
    }
    this.tags.push({ tagKey: '', tagValue: '' });
  }

  deleteTag(index: number, e: MouseEvent): void {
    if (e) {
      e.preventDefault();
    }
    this.tags.splice(index, 1);
  }

  onSearch(): void {
    let aggregateQuery: AggregateQuery = new AggregateQuery();

    aggregateQuery.arithmeticType = this.arithmeticType;
    aggregateQuery.metric = this.selectedMetric;

    this.tags.forEach(function (tag) {
      if (tag.tagKey !== '' && tag.tagValue !== '') {
        if (!aggregateQuery.tags[tag.tagKey]) {
          aggregateQuery.tags[tag.tagKey] = [tag.tagValue];
        } else {
          aggregateQuery.tags[tag.tagKey].push(tag.tagValue);
        }
      }
    });

    console.log(aggregateQuery);

    this.httpClient    
      .post<AggregateResult[]>('/api/v1/merge/aggregate/query', aggregateQuery, {})
      .subscribe((results: AggregateResult[]) => {
        console.log(results);
        this.aggregateResults = results;
      });
  }
}
